import { BASE_URL } from "@/config/base";
import type { RequestResult } from "@/types/requstParm";
//服务器接口地址
// 封装公共请求方法
function request(
  url: string,
  method: "GET" | "POST" | undefined = "GET",
  data?: object | any
) {
  return new Promise<RequestResult<any>>(function (resolve, reject) {
    // uni.showLoading();
    let header: any;
    if (
      uni.getStorageSync("token") !== undefined &&
      uni.getStorageSync("token") !== ""
    ) {
      header = {
        "content-type": "application/json",
        Token: uni.getStorageSync("token"),
      };
    } else {
      header = {
        "content-type": "application/json",
      };
    }
    uni.request({
      url: BASE_URL + "/index.php/api" + url,
      method: method,
      data: data,
      header: header,
      timeout: 5000,
      success(res: any) {
        // uni.hideLoading();
        if (res.data.code === 0) {
          resolve(res.data);
        } else {
          //其他异常
          uni.showToast({
            title: res.data.msg,
            icon: "none",
          });
          reject(res.data);
        }
      },
      fail(err) {
        // uni.hideLoading();
        //请求失败
        uni.showToast({
          title: "无法连接到服务器",
          icon: "none",
        });
        reject(err);
      },
    });
  });
}
export default request;
